package com.airsystem.pos.bengkel.service;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.airsystem.pos.bengkel.entity.JenisTagihan;
import com.airsystem.pos.bengkel.entity.Tagihan;
import com.airsystem.pos.bengkel.interfaces.IParser;
import com.airsystem.pos.bengkel.interfaces.IServices;
import com.airsystem.pos.bengkel.service.parser.TagihanParser;
import com.airsystem.pos.bengkel.util.HibernateUtil;

/**
 * @author Fanny Irawan Sutawanir (fannyirawans@gmail.com)
 */
public class TagihanServices implements IServices<Tagihan> {
	private static final Logger LOG = Logger.getLogger(TagihanServices.class.getSimpleName());

	private static final StringBuffer SELECT = new StringBuffer("FROM Tagihan ").append(Tagihan.ALIAS).append(" JOIN ")
																				.append(Tagihan.ALIAS).append(".jenis_tagihan ")
																				.append(JenisTagihan.ALIAS).append(" WHERE %s LIKE '%s'");

	IParser<Tagihan, Object> parser;

	public TagihanServices() {
		parser = new TagihanParser();
	}

	public void saveOrUpdate(Tagihan data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.saveOrUpdate(data);
			session.flush();
		} finally {
			session.close();
		}
	}

	public void delete(Tagihan data) {
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			session.delete(data);
			session.flush();
		} finally {
			session.close();
		}
	}

	public Iterable<Tagihan> select(Tagihan data) {
		List<Tagihan> list = new LinkedList<Tagihan>();
		Session session = HibernateUtil.getSessionFactory().openSession();

		try {
			StringBuffer LIKE = new StringBuffer("%");
			LIKE.append(data.getSearchKeyword());
			LIKE.append("%");

			String temp = String.format(SELECT.toString(), data.getSearchColumn(), LIKE.toString());
			List<?> query = (List<?>) session.createQuery(temp).list();

			for (Object result : query) {
				if (isArray(result)) {
					parser = new TagihanParser();
					list.add(parser.doParse(result));
				} else {
					LOG.info("No array result is " + result.toString());

					continue;
				}
			}
		} finally {
			session.close();
		}

		return list;
	}

	private boolean isArray(Object object) {
		return object.getClass().isArray();
	}
}